package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.dto.PrivateMessageDTO;
import com.example.pt.service.PrivateMessageService;
import com.example.pt.utils.JWTUtil;
import com.example.pt.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 私信控制器
 */
@RestController
@RequestMapping("/api/message")
@CrossOrigin(origins = "*")
public class PrivateMessageController {

    @Autowired
    private PrivateMessageService privateMessageService;

    /**
     * 发送私信
     * @param params 参数
     * @return 发送的消息
     */
    @PostMapping("/send")
    public Result<PrivateMessageDTO> sendMessage(@RequestBody Map<String, Object> params,
                                                 @RequestHeader Map<String, String> header) {
        // 从request中获取当前用户ID
        String token =  header.get("token");
        System.out.println(token);
        DecodedJWT decode;
        Map<String, Object> response = new HashMap<>();

        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {

            response.put("token", "登录权限已失效！");
            return  Result.fail("令牌失效：" + e.getMessage());
        }
        int userId = decode.getClaim("uid").asInt();

        // 获取接收者ID和消息内容
        Integer receiverId = Integer.valueOf(params.get("receiverId").toString());
        String content = (String) params.get("content");
        
        if (content == null || content.trim().isEmpty()) {
            return Result.fail("消息内容不能为空");
        }
        
        try {
            PrivateMessageDTO message = privateMessageService.sendMessage(userId, receiverId, content);
            return Result.success(message);
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail("发送失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取与指定用户的聊天记录
     * @param userId 对方用户ID
     * @return 聊天记录
     */
    @GetMapping("/chat/{userId}")
    public Result<List<PrivateMessageDTO>> getConversationMessages(@PathVariable Integer userId,
                                                                   @RequestHeader Map<String, String> header) {
        String token =  header.get("token");
        DecodedJWT decode;
        Map<String, Object> response = new HashMap<>();

        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {

            response.put("token", "登录权限已失效！");
            return  Result.fail("令牌失效：" + e.getMessage());
        }
        int currentuserId = decode.getClaim("uid").asInt();
        
        try {
            List<PrivateMessageDTO> messages = privateMessageService.getConversationMessages(currentuserId, userId);
            return Result.success(messages);
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail("获取聊天记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取会话列表
     * @return 会话列表
     */
    @GetMapping("/conversations")
    public Result<List<PrivateMessageDTO>> getConversationList(@RequestHeader Map<String, String> header) {

        String token =  header.get("token");
        DecodedJWT decode;
        Map<String, Object> response = new HashMap<>();

        try {
            decode = JWTUtil.verifyToken(token);
        } catch (Exception e) {

            response.put("token", "登录权限已失效！");
            return  Result.fail("令牌失效：" + e.getMessage());
        }
        int userId = decode.getClaim("uid").asInt();
        try {
            List<PrivateMessageDTO> conversations = privateMessageService.getConversationList(userId);
            return Result.success(conversations);
        } catch (Exception e) {
            return Result.fail("获取会话列表失败：" + e.getMessage());
        }
    }
    /*
    @GetMapping("/conversations")
    public Result<List<PrivateMessageDTO>> getConversationList(HttpServletRequest request) {
        // 从request中获取当前用户ID
        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return Result.fail("未登录");
        }
        
        try {
            List<PrivateMessageDTO> conversations = privateMessageService.getConversationList(userId);
            return Result.success(conversations);
        } catch (Exception e) {
            return Result.fail("获取会话列表失败：" + e.getMessage());
        }
    }*/
    
    /**
     * 标记会话为已读
     * @param userId 对方用户ID
     * @param request HTTP请求
     * @return 结果
     */
    @PostMapping("/read/{userId}")
    public Result<Boolean> markConversationAsRead(@PathVariable Integer userId, HttpServletRequest request) {
        // 从request中获取当前用户ID
        Integer currentUserId = (Integer) request.getAttribute("uid");
        if (currentUserId == null) {
            return Result.fail("未登录");
        }
        
        try {
            boolean success = privateMessageService.markConversationAsRead(currentUserId, userId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.fail("标记已读失败：" + e.getMessage());
        }
    }
} 